<?php

/**
 * Description of QuoteModel
 *
 * @author NE
 */
class Backend_QuoteModel extends RCMS_Core_BaseModel {
	protected $_name = 'shopping_quote';

	public function selectAllQuotes() {
		$select = $this->getAdapter()->select()
			->from(
				array('sc' => 'shopping_quote'),
				array(
					'id',
					'name',
					'status',
					'content',
					'date',
                    'last_edited_by'
				)
			);
		return $this->getAdapter()->fetchAll($select);
	}

	public function selectShoppingConfig()
    {
        $sql = $this->_adapter->select()->from('shopping_config');
        return $this->_adapter->fetchPairs($sql);
    }

	public function selectSystemConfig() {
		$sql = $this->_adapter->select()->from('config');
        return $this->_adapter->fetchPairs($sql);
	}

	public function getQuotesList($condition = false, $order = false, $limit = false) {
		$select = $this->getAdapter()->select()->from($this->_name, array('id','name','status','(content <> "" AND content IS NOT NULL) as preview','date','last_edited_by','id','id'));
		if ($condition) {
			foreach ($condition['fields'] as $c) {
				$select->orWhere($c.' LIKE ?', '%'.$condition['search'].'%');
			}
		}

		if ($order) {
			$select->order($order);
		}

		if ($limit) {
			$select->limit($limit['count'], $limit['offset']);
		}

		return $this->getAdapter()->fetchAll($select);
	}

	public function getAddressList(){
		$select = $this->getAdapter()->select()->from(array('q'=>$this->_name),array('id', 'name'))
			->joinLeft(array('c'=>'shopping_usercart'), 'c.id = q.sc_id', array('name','email', 'company', 'address1', 'address2', 'country', 'state', 'city', 'zip', 'phone'));
		
		return $this->getAdapter()->fetchAll($select);
	}

	public function getDataForQuote($where) {
		$sql = $this->getAdapter()->select()->from(array('q'=>$this->_name), array('q.id'))
			->joinLeft(array('c' => 'shopping_usercart'), 'c.id = q.sc_id', array(
				'billing_name' => 'name',
				'billing_email' => 'email',
				'billing_company' => 'company',
				'billing_address1' => 'address1',
				'billing_address2' => 'address2',
				'billing_country'  => 'country',
				'billing_state' => 'state',
				'billing_city' => 'city',
			 	'billing_zip' => 'zip',
				'billing_phone' => 'phone'
				))
			->joinLeft(array('s' => 'shopping_shipping'), 's.cart_id = c.id', array('shipping_address'));
		if (is_numeric($where)) {
			$sql->where('q.id = ?', (int)$where);
		}
		$sql->orWhere('q.name LIKE ?', "%$where%")
			->orWhere('c.email LIKE ?', "%$where%")
			//->orWhere('s.shipping_address LIKE ?', "%$where%")
			->group('billing_email')
			->order('q.date DESC');
		return $this->getAdapter()->fetchAll($sql);
	}
	
	public function getQuotesCount(){
		$sql = $this->getAdapter()->select()->from($this->_name,'COUNT(id)');
		return $this->getAdapter()->fetchOne($sql);
	}

}
